package common

import (
	"fmt"
	"github.com/jinzhu/gorm"
	"github.com/spf13/viper"
	"jiaqin/model"
)

var DB *gorm.DB

func InitDB() *gorm.DB  {
	driverName := viper.GetString("datasource.driverName")
	host:=viper.GetString("datasource.host")
	port:=viper.GetString("datasource.port")
	database:=viper.GetString("datasource.database")
	username:=viper.GetString("datasource.username")
	password:=viper.GetString("datasource.password")
	charset:=viper.GetString("datasource.charset")
	args := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=true",
		username,
		password,
		host,
		port,
		database,
		charset)

	db, err:=gorm.Open(driverName,args) //gorm一定要下 github.com/jinzhu/gorm  不然会报错
	if err != nil {
		panic("failed to connect database, err: "+err.Error())
	}
	db.AutoMigrate(&model.User{}) //自动创建数据表
	DB = db
	return db
}

func GetDB() *gorm.DB { //该方法用于获取DB实例
	return DB
}